<template>
  <div class="customer-container">
    <!-- 查询 -->
    <div class="search-container">
      <el-select
          v-model="selectedCategory"
          placeholder="客户分类"
          @change="fetchCustomers"
          style="width: 150px"
          class="search-select"
      >
        <el-option
            v-for="category in categories"
            :key="category.value"
            :label="category.label"
            :value="category.value"
        ></el-option>
      </el-select>
      <el-input
          placeholder="请输入客户姓名"
          style="width: 200px"
          v-model="queryName"
          class="search-input"
      ></el-input>
      <el-button
          @click="queryByName"
          type="success"
          plain
          class="search-button"
      >
        查询
      </el-button>
<!--      <el-button-->
<!--          @click="showCustomerDialog"-->
<!--          type="primary"-->
<!--          class="register-button"-->
<!--      >-->
<!--        登记-->
<!--      </el-button>-->
    </div>

    <!-- 错误信息 -->
    <div class="error-message">{{ errorMessage }}</div>

    <!-- 客户信息表格 -->
    <el-table
        :data="customerList"
        class="customer-table"
        header-cell-class-name="table-header"
    >
      <el-table-column
          label="序号"
          type="index"
          width="60px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="customerName"
          label="客户姓名"
          width="100px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="customerSex"
          label="性别"
          width="80px"
          align="center"
      >
        <template #default="scope">
          {{ scope.row.customerSex === 0 ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column
          prop="customerAge"
          label="年龄"
          width="80px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="buildingNo"
          label="所属楼房"
          width="100px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="checkinDate"
          label="入住日期"
          width="120px"
          align="center"
          :formatter="formatDate"
      ></el-table-column>
      <el-table-column
          prop="expirationDate"
          label="合同到期时间"
          width="120px"
          align="center"
          :formatter="formatDate"
      ></el-table-column>
      <el-table-column
          prop="contactTel"
          label="联系电话"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="familyMember"
          label="家属"
          width="80px"
          align="center"
      ></el-table-column>
      <el-table-column label="操作" width="200px" align="center">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click="showDetailDialog(scope.row.id)"
              class="detail-button"
          >
            查看
          </el-button>
          <el-button
              type="primary"
              size="small"
              @click="showEditDialog(scope.row.id)"
              class="edit-button"
          >
            修改
          </el-button>
<!--          <el-button-->
<!--              type="danger"-->
<!--              size="small"-->
<!--              @click="confirmDelete(scope.row.id)"-->
<!--              class="delete-button"-->
<!--          >-->
<!--            删除-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="pageContains.pageNum"
          v-model:page-size="pageContains.pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageContains.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          class="pagination"
      />
    </div>

    <!-- 客户信息对话框 -->
    <el-dialog
        v-model="customerDialog"
        :title="dialogTitle"
        class="customer-dialog"
    >
      <el-form :model="curCustomer" class="customer-form">
        <el-form-item label="客户姓名" class="form-item">
          <el-col :span="11">
            <el-input v-model="curCustomer.customerName" class="form-input" :disabled="dialogOptType === 3"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="性别" class="form-item">
          <el-col :span="11">
            <el-select v-model="curCustomer.customerSex" class="form-select" :disabled="dialogOptType === 3">
              <el-option
                  v-for="item in sexOptions"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="年龄" class="form-item">
          <el-col :span="11">
            <el-input v-model="curCustomer.customerAge" class="form-input" :disabled="dialogOptType === 3"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="身份证号" class="form-item">
          <el-col :span="11">
            <el-input v-model="curCustomer.idcard" class="form-input" :disabled="dialogOptType === 3"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="所属楼房" class="form-item">
          <el-col :span="11">
            <el-input v-model="curCustomer.buildingNo" class="form-input" :disabled="dialogOptType === 3"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="入住日期" class="form-item">
          <el-col :span="11">
            <el-date-picker
                v-model="curCustomer.checkinDate"
                class="form-date-picker"
                :disabled="dialogOptType === 3"
            ></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="合同到期时间" class="form-item">
          <el-col :span="11">
            <el-date-picker
                v-model="curCustomer.expirationDate"
                class="form-date-picker"
                :disabled="dialogOptType === 3"
            ></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="联系电话" class="form-item">
          <el-col :span="11">
            <el-input v-model="curCustomer.contactTel" class="form-input" :disabled="dialogOptType === 3"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="家属" class="form-item">
          <el-col :span="11">
            <el-input v-model="curCustomer.familyMember" class="form-input" :disabled="dialogOptType === 3"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="备注" class="form-item">
          <el-col :span="11">
            <el-input
                type="textarea"
                v-model="curCustomer.attention"
                class="form-input"
                :disabled="dialogOptType === 3"
            ></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="closeCustomerDialog" class="dialog-button">关闭</el-button>
        <el-button v-if="dialogOptType === 2" type="primary" @click="optOne" class="dialog-button">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import http from '@/axios/http';
import qs from "qs";
import { ElMessage, ElMessageBox } from 'element-plus';

// 存放客户数据集合
let customerList = ref([]);

// 报错提示
let errorMessage = ref("");

// 模糊查询绑定的客户名称
let queryName = ref("");

// 客户分类
let selectedCategory = ref("all");
let categories = ref([
  { label: "历史客户", value: "all" },
  { label: "在住客户", value: "active" },
  { label: "已退住客户", value: "inactive" },
]);

// 对话框显示控制
let customerDialog = ref(false);

// 客户信息，或者编辑已有客户的绑定数据
let curCustomer = ref({
  customerName: "",
  customerSex: null,
  customerAge: null,
  idcard: "",
  buildingNo: "",
  checkinDate: null,
  expirationDate: null,
  contactTel: "",
  familyMember: "",
  attention: "",
});

// 登记、修改客户信息弹出框的标题和操作按钮显示文字
let dialogTitle = ref("");
let buttonOpt = ref("");

// 对话框操作类型：1：添加 2：编辑 3：查看
let dialogOptType = ref(1);

// 分页相关
let pageContains = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 性别数组
let sexOptions = ref([
  {
    label: '男',
    value: 0
  },
  {
    label: '女',
    value: 1
  }
]);

// 根据客户姓名模糊查询客户信息
function queryByName() {
  let param = {
    customerName: queryName.value,
    size: pageContains.value.pageSize,
    pageNum: pageContains.value.pageNum,
    pageSize: pageContains.value.pageSize,
  };
  http.post('/lyy/get_customers_by', param).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      pageContains.value = result.data;
      customerList.value = result.data.list;
    } else {
      errorMessage.value = result.error;
    }
  });
}

// 根据分类获取客户信息
function fetchCustomers() {
  let param = {
    size: pageContains.value.pageSize,
    pageNum: pageContains.value.pageNum,
    pageSize: pageContains.value.pageSize,
    category: selectedCategory.value
  };
  http.post('/lyy/get_customers_by_category', param).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      pageContains.value = result.data;
      customerList.value = result.data.list;
    } else {
      errorMessage.value = result.error;
    }
  });
}

// 显示客户信息对话框
function showCustomerDialog() {
  dialogTitle.value = "客户入住登记";
  buttonOpt.value = "录入";
  customerDialog.value = true;
  dialogOptType.value = 1; // 设置当前操作类型标志是录入
}

// 关闭客户信息对话框
function closeCustomerDialog() {
  customerDialog.value = false;
}

// 页面初始化
onMounted(() => {
  init();
});

function init() {
  fetchCustomers();
}

// 格式化日期
function formatDate(row, column) {
  let data = row[column.property];
  if (data == null) {
    return null;
  }
  let dt = new Date(data);
  return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate();
}

// 记录客户信息
function recordOne() {
  let param = curCustomer.value;
  http.post('/lyy/add_one_customer', param).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      closeCustomerDialog();
      fetchCustomers();
    } else {
      errorMessage.value = result.error;
    }
  });
}

// 显示编辑对话框
function showEditDialog(customerid) {
  getCustomerInfo(customerid);
  customerDialog.value = true;
  dialogTitle.value = "客户入住信息修改";
  buttonOpt.value = "修改";
  dialogOptType.value = 2; // 设置当前操作类型标志是修改
}

// 显示详细信息对话框
function showDetailDialog(customerid) {
  getCustomerInfo(customerid);
  dialogTitle.value = "客户详细信息";
  buttonOpt.value = "关闭";
  customerDialog.value = true;
  dialogOptType.value = 3; // 3: 查看
}

// 获取客户信息
function getCustomerInfo(customerid) {
  let param = {
    customerid: customerid
  };
  http.post('/lyy/getcustomerby_iid', qs.stringify(param)).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      curCustomer.value = result.data;
    } else {
      errorMessage.value = result.error;
    }
  }).catch((error) => {
    console.error('获取客户信息出错:', error);
    errorMessage.value = '网络请求出错，请稍后重试';
  });
}

// 编辑客户信息
function editOne() {
  let param = curCustomer.value;
  http.post('/lyy/modifycustomerby_id', param).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      closeCustomerDialog();
      fetchCustomers();
    } else {
      errorMessage.value = result.error;
    }
  });
}

// 操作按钮
function optOne() {
  if (dialogOptType.value === 1) {
    recordOne();
  } else if (dialogOptType.value === 2) {
    editOne();
  }
}

// 分页处理
const handlePageChange = (pageNum1) => {
  pageContains.value.pageNum = pageNum1;
  fetchCustomers();
};

const handleSizeChange = (pageSize1) => {
  pageContains.value.pageSize = pageSize1;
  fetchCustomers();
};

// 删除客户信息
function confirmDelete(customerid) {
  ElMessageBox.confirm('确定要删除此客户信息吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    removeCustomer(customerid);
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

function removeCustomer(customerid) {
  http.post('/lyy/removecustomer_by_id', qs.stringify({ customerid })).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      ElMessage.success('删除成功');
      fetchCustomers();
    } else {
      ElMessage.error(result.error || '删除失败');
    }
  }).catch((error) => {
    console.error('删除客户信息出错:', error);
    ElMessage.error('网络请求出错，请稍后重试');
  });
}
</script>

<style scoped>
.customer-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  margin-right: 10px;
}

.search-button {
  margin-right: 20px;
}

.register-button {
  width: 100px;
  font-weight: bold;
  font-size: 16px;
}

.error-message {
  color: #f56c6c;
  margin-bottom: 20px;
  text-align: center;
}

.customer-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.table-header {
  background-color: #f0f2f5;
  font-weight: bold;
  color: #333;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination {
  width: 100%;
}

.customer-dialog {
  width: 500px;
}

.customer-form {
  width: 100%;
}

.form-item {
  margin-bottom: 20px;
}

.form-input,
.form-select,
.form-date-picker {
  width: 100%;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

.dialog-button {
  width: 100%;
  padding: 10px;
}
</style>